<?php

namespace app\queue\stomp;

use app\queue\BaseConsumer;
use common\service\UserService;
use Exception;
use support\bootstrap\Redis;
use Webman\Stomp\RetryAbleConsumer;
use malkusch\lock\mutex\PHPRedisMutex;

/**
 * 同步用户到saas
 */
class SyncUserConsumer extends BaseConsumer implements RetryAbleConsumer
{

    // 要消费的队列名
    public $queue = 'sync_user';

    // 连接名，对应 config/redis_queue.php 里的连接`
    public $connection = 'default';

    /**
     * @param $data
     * @return void
     * @throws Exception
     */
    public function doConsume($data)
    {
        $userIdList = $data['user_id_list'];
        foreach ($userIdList as $userId) {
            $checkKey = $this->queue . ':' . $userId;
            $mutex = new PHPRedisMutex([Redis::connection()->client()], $checkKey, $this->getTtr());
            return $mutex->synchronized(function () use ($userId) {
                UserService::getInstance()->getUserByUnionId($userId, true);
            });
        }
    }

    /**
     * 重试间隔
     * @return int
     */
    public function getTtr()
    {
        return 60;
    }

    /**
     * 能否重试
     * @param $attempt
     * @param $error
     * @return bool
     */
    public function canRetry($attempt, $error)
    {
        trace(format_exception_info($error), 'ERR');
        return $attempt <= 5;
    }
}
